/**
 * 工具函数集合
 */

/**
 * 日期格式化
 */
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) return ''
  
  const d = new Date(date)
  if (isNaN(d.getTime())) return ''
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 金额格式化
 */
export const formatMoney = (amount, decimals = 2) => {
  if (amount === null || amount === undefined) return '0.00'
  
  const num = parseFloat(amount)
  if (isNaN(num)) return '0.00'
  
  return num.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

/**
 * 手机号格式化
 */
export const formatPhone = (phone) => {
  if (!phone) return ''
  const str = String(phone)
  return str.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}

/**
 * 验证手机号
 */
export const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

/**
 * 验证身份证号
 */
export const validateIdCard = (idCard) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return reg.test(idCard)
}

/**
 * 防抖函数
 */
export const debounce = (func, wait = 300) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 */
export const throttle = (func, limit = 300) => {
  let inThrottle
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 深拷贝
 */
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

/**
 * 生成随机字符串
 */
export const randomString = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 复制到剪贴板
 */
export const copyToClipboard = (text) => {
  return new Promise((resolve) => {
    uni.setClipboardData({
      data: text,
      success: () => {
        uni.showToast({
          title: '复制成功',
          icon: 'success'
        })
        resolve(true)
      },
      fail: () => {
        uni.showToast({
          title: '复制失败',
          icon: 'none'
        })
        resolve(false)
      }
    })
  })
}

/**
 * 显示确认对话框
 */
export const showConfirm = (content, title = '提示') => {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

/**
 * 检查余额是否足够支付
 * @param {number|string} depositNum - 需要支付的金额
 * @param {string} navigateUrl - 余额不足时跳转的页面路径，默认为充值页面
 * @returns {Promise<boolean>} 返回true表示余额足够，false表示余额不足
 * 
 * @example
 * // 基本用法
 * const isSufficient = await checkBalance(1000)
 * if (isSufficient) {
 *   // 余额足够，继续处理
 *   processOrder()
 * }
 * 
 * // 自定义跳转页面
 * const isSufficient = await checkBalance(1000, '/pages/mine/depositOut/index')
 * 
 * // 在方法中使用
 * async submitOrder() {
 *   const isBalanceSufficient = await checkBalance(this.getDepositNum())
 *   if (!isBalanceSufficient) return
 *   
 *   // 继续处理订单
 *   this.processOrder()
 * }
 */
export const checkBalance = (depositNum, navigateUrl = '/pages/mine/depositIn/index') => {
  return new Promise((resolve) => {
    const customerInfo = uni.getStorageSync('customerInfo');
	if(!customerInfo){
		uni.showToast({
		  title: '请先登录',
		  icon: 'none'
		})
		return;
	}
    if (!customerInfo.balance) {
      uni.showToast({
        title: '用户信息获取失败',
        icon: 'none'
      })
      resolve(false)
      return
    }

    if (Number(depositNum) > Number(customerInfo.balance)) {
      uni.showModal({
        title: '提示',
        content: '您余额不足以支付定金,请先入款',
        confirmText: '去存',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: navigateUrl
            })
          }
          resolve(false)
        }
      })
    } else {
      resolve(true)
    }
  })
}

export default {
  formatDate,
  formatMoney,
  formatPhone,
  validatePhone,
  validateIdCard,
  debounce,
  throttle,
  deepClone,
  randomString,
  copyToClipboard,
  showConfirm,
  checkBalance
} 